<template>
  <!--新增/编辑跟进-->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :title="title2"
      :beforeClose="handleClose2"
      :visible.sync="dialogVisible2"
      width="1000px">
      <el-form :model="trackingForm" size="mini" label-width="110px" :rules="rules" ref="trackingForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称：" v-if="popType != 'addMy'">
              {{trackingForm.customerName}}
            </el-form-item>
            <el-form-item label="客户名称：" v-else prop="customerId">
              <el-select
                @change="changeCustomer"
                clearable
                v-model="trackingForm.customerId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="querySearch">
                <el-option
                  v-for="item in querySearchList"
                  :key="item.customerId"
                  :label="item.customerName"
                  :value="item.customerId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="产品线：" prop="cglId" v-if="popType != 'edit'">
              <el-select v-model="trackingForm.cglId" @change="changecglId" multiple>
                <el-option :label="item.goodsLineName + '/' + item.cglCurrentDevelopStateStr" v-for="item in goodsLineList" :value="item.cglId" :key="item.cglId"></el-option>
              </el-select>
              <el-button type="text" style="margin-left:10px" @click="showGoodsLine('add','')">新增</el-button>
            </el-form-item>
            <el-form-item label="产品线：" v-else>
              {{trackingForm.goodsLineName}}
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人：" prop="contactId">
              <el-select  v-model="trackingForm.contactId"  placeholder="请先选择产品线" @change="changeContactId" style="width:150px;">
                <el-option v-for="item in contactList"  :key="item.contactId" :label="item.contactName" :value="item.contactId"></el-option>
              </el-select>
              <el-button type="text" style="margin-left:10px" @click="showAddLxr('add','')">新增</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="跟进方式：" prop="trackingTypeId">
              <el-select  v-model="trackingForm.trackingTypeId" placeholder="请选择" clearable>
                <el-option v-for="item in customerTrackingList"  :value="item.cddId" :label="item.cddValue" :key="item.cddId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>



        <!--      <el-row >-->
        <!--        <el-col :span="16">-->
        <!--            <el-form-item label="是否有采购决定权：" label-width="120px">-->
        <!--              <span style="font-size:12px" v-if="isBuyPermission != -1">{{isBuyPermission==1 ? '是' : '否'}}</span>-->
        <!--            </el-form-item>-->
        <!--        </el-col>-->
        <!--      </el-row>-->

        <el-row>
          <el-col :span="8">
            <el-form-item label="跟进类型：" prop="isInvalid">
              <el-radio-group v-model="trackingForm.isInvalid">
                <el-radio :label="0">有效</el-radio>
                <el-radio :label="1">无效</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开发阶段：" prop="developStep">
              <el-select  v-model="trackingForm.developStep" placeholder="请选择" @change="changeDevelopStep">
                <el-option v-for="item in developSteps" :value="item.id" :label="item.name" :key="item.id" v-if="item.id > 0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="trackingForm.developStep == 40">
            <el-form-item label="客户原因："  prop="fromBuyReason">
              <el-select  v-model="trackingForm.fromBuyReason" placeholder="请选择">
                <el-option v-for="item in fromBuyReasonList"  :value="item.cddId" :label="item.cddValue" :key="item.cddId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="跟进内容：" prop="trackingContent">
          <el-input v-model="trackingForm.trackingContent" :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="关键人信息：" v-if="trackingForm.developStep == 10">
          <el-table :data="lxrlist" border style="width: 100%; margin-bottom: 20px" size="small" :loading="lxrlistLoading">
            <el-table-column
              label="产品线"
              align="center"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.goodsLineName}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="联系人"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.contactName}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="手机号"
              min-width="150">
              <template slot-scope="scope">
                {{scope.row.contactMobile}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="电话"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.contactPhone}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="职务"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.contactDuty}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="主联系人"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.isMainContact == 1 ? '是' : '否'}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="采购决定权"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.isBuyPermission == 1 ? '有' : '没有'}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="关注点"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.contactFocus}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="生日"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.contactBirthday}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="爱好"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.contactHobby}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="状态"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.isLeaveJob == 0 ? '在职' : '离职'}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="更新时间"
              min-width="150">
              <template slot-scope="scope">
                {{scope.row.updatedAt}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="更新人"
              min-width="100">
              <template slot-scope="scope">
                {{scope.row.updateUserName}}
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              min-width="100">
              <template slot-scope="scope">
                <el-button type="text" @click="showAddLxr('edit',scope.row)" v-if="scope.row.isCanUpdate == 1">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container" style="margin-top:0">
            <el-pagination
              background
              @size-change="lxrhandleSizeChange"
              @current-change="lxrhandleCurrentChange"
              layout="total, sizes,prev, pager, next,jumper"
              :page-size="lxrlistQuery.pageSize"
              :page-sizes="[10,15,20]"
              :current-page.sync="lxrlistQuery.pageNum"
              :total="lxrcount">
            </el-pagination>
          </div>
        </el-form-item>
        <el-form-item label="需求信息：" v-if=" trackingForm.developStep == 20">
          <table cellspacing="0" cellpadding="0" border="0" style="width:100%">
            <tr>
              <td>产品线</td>
              <td>产品匹配度</td>
              <td>竞争对手情况</td>
              <td>竞争类型</td>
              <td>月使用量</td>
              <td>付款方式</td>
              <td>使用材料</td>
            </tr>
            <tr v-for="ee in trackingForm.goodsLineList" :key="ee.cglId">
              <td style="height:40px;width:80px">{{ee.goodsLineName}}</td>
              <td style="height:40px;">
                <el-select v-model="ee.goodsMatchDegree">
                  <el-option v-for="(item,index) in goodsMatchDegreeList" :value="item.cddValue" :label="item.cddValue" :key="item.cddValue"></el-option>
                </el-select>
              </td>
              <td>
                <el-select v-model="ee.cglCompetitorInfo" size="small" style="width:100px;" >
                  <el-option v-for="item in cglCompetitorInfoList"  :value="item.cddId" :label="item.cddValue" :key="item.cddId"></el-option>
                </el-select>
              </td>

              <td>
                <el-radio-group v-model="ee.cglCompetitorType" size="small">
                  <el-radio :label="item.cddValue" v-for="item in cglCompetitorTypeList" :key="item.cddValue">{{ item.cddValue }}</el-radio>
                </el-radio-group>
              </td>
              <td>
                <el-input v-model="ee.cglMonthBuyNum" style="width:100px;" size="small"></el-input>
              </td>
              <td>
                <el-select v-model="ee.cglPayMethod" clearable size="small" style="width:100px;" >
                  <el-option v-for="item in payMethodList"  :value="item.cddValue" :label="item.cddValue" :key="item.cddValue"></el-option>
                </el-select>
              </td>
              <td>
                <el-select v-model="ee.goodsSn" placeholder="请选择" clearable filterable size="small" style="width:100px;" >
                  <el-option
                    v-for="item in goodsList"
                    :key="item.kingId"
                    :label="item.goodsSn"
                    :value="item.goodsSn">
                  </el-option>
                </el-select>
              </td>
            </tr>
          </table>
        </el-form-item>
        <el-form-item label="建立粘度：" v-if="trackingForm.developStep == 30">
          <el-checkbox-group v-model="trackingForm.relationTypeIds" >
            <div class="check-item" v-for="item in ldList" :key="item.cddId">
              <el-checkbox :label="item" @change="changerelationTypeIds(item,$event)"> </el-checkbox>
              <div class="label">{{item.cddValue}}</div>
            </div>
          </el-checkbox-group>
          <el-table :data="ldchcecklist" border style="width: 100%; margin-bottom: 20px" size="small">
            <el-table-column
              label="产品线"
              align="center"
              width="100">
              <template slot-scope="scope">
                {{scope.row.goodsLineName}}
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              label="粘度">
              <template slot-scope="scope">
                <el-tag
                  @close="closeSpan(scope.$index,index)"
                  v-for="(tag,index) in scope.row.chcecklist" :key="tag.name" closable size="mini" class="chceckspan" :title="tag.cddValue">
                  {{tag.cddValue}}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="促成交：" v-if="trackingForm.developStep == 40">
          <el-form-item label="对比价格" label-width="60px">
            <el-radio-group v-model="trackingForm.dealComparePrice" @change="changedealComparePrice">
              <el-radio :label="item" v-for="item in jgList" :key="item.cddId">{{ item.cddValue }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="付款条件" label-width="60px">
            <el-checkbox-group v-model="trackingForm.dealPayMethod">
              <el-checkbox :label="item" v-for="item in fkList" :key="item.cddId" @change="changeDealPayMethod(item,$event)">{{item.cddValue}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-table :data="ccjlist" border style="width: 100%; margin-bottom: 20px" size="small">
            <el-table-column
              label="产品线"
              align="center"
              width="100">
              <template slot-scope="scope">
                {{scope.row.goodsLineName}}
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              label="对比价格">
              <template slot-scope="scope">
                <el-tag
                  @close="closeSpanJg(scope.$index,index)"
                  v-for="(tag,index) in scope.row.dealComparePrice" :key="tag.cddId" closable size="mini" class="chceckspan" :title="tag.cddValue">
                  {{tag.cddValue}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              label="付款条件">
              <template slot-scope="scope">
                <el-tag
                  @close="closeSpanFk(scope.$index,index)"
                  v-for="(tag,index) in scope.row.dealPayMethod" :key="tag.cddId" closable size="mini" class="chceckspan chceckspan2" :title="tag.cddValue">
                  {{tag.cddValue}}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

        </el-form-item>

        <el-form-item label="图片上传：" >
          <div style="width:80px;height:80px;margin-bottom:10px;margin-right:10px;vertical-align: middle;position: relative;display:inline-block" v-for="(item,index) in trackingForm.trackingPics">
            <img :src="item"  style="width:100%;height:100%;object-fit: contain;"/>
            <i class="el-icon-error" style="cursor: pointer;position: absolute;right:0;top:0;" @click="delImg(index)"></i>
          </div>
          <el-upload
            v-if="trackingForm.trackingPics.length<9"
            drag
            action="https://upload.qiniup.com"
            :data="uploadToken"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="下次跟进日期：">
          <el-date-picker
            v-model="trackingForm.nextTrackingTime"
            align="right"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="trackingForm.trackingRemark"  :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>
    <addGoodsLine ref="addGoodsLine" @getList="getList"></addGoodsLine>
    <addLxr ref="addLxr" @getList="getContactListData('add')"></addLxr>
  </div>

</template>
<script>
import {getQiniuToken,saveTrackingInfo,getContactList,getCustomerSetting,orderGoodsList,getCustomerOption} from '@/api/partner'
import {goodsLineAddTracking,developGoodsLineList,goodsLineListById,customerNewContactList,goodsLineLdHCcjInfo} from '@/api/company'
import {validatePhone} from '@/utils/validate';
import {formatDate} from '@/utils/date';
import addGoodsLine from './addGoodsLine'
import addLxr from './addLxr'
import store from '@/store'
import { mapGetters } from 'vuex'



const defaultTrackingForm = {
  cglId:[],
  customerId:'',
  customerName:'',
  contactId:'',
  trackingTypeId:'',
  trackingContent:'',
  trackingTime:'',
  trackingPics:[],
  trackingRemark:'',
  nextTrackingTime:'',
  goodsLineName:'',
  cglScale:'',
  cglOperatingRate:'',
  cglCompetitorInfo:'',
  cglCompetitorType:'',
  cglMonthBuyNum:'',
  cglPayMethod:'',
  goodsSn:'',
  isInvalid:0,
  developStep:'',
  fromBuyReason:'',
  goodsLineList:[],

  relationTypeIds:[], //建立粘度
  dealComparePrice:'', //对比价格
  dealPayMethod:[],//付款条件

};

const defaultLxrListQuery={
  cglId:[],
  "pageNum" : 1,
  "pageSize" : 10
};

export default {
  name: "index",
  data(){
    const isvalidatePhone = (rule, value, callback) => {
      if(!validatePhone(value)){
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    };
    return {
      dialogVisible2:false,
      title2:'',
      btnLoading2:false,
      trackingForm:JSON.parse(JSON.stringify(defaultTrackingForm)),
      rules:{
        customerName:[{required: true, message: '请选择客户', trigger: 'change'},],
        contactId:[{required: true, message: '请选择联系人', trigger: 'change'},],
        trackingTypeId:[{required: true, message: '请选择跟进方式', trigger: 'change'},],
        trackingContent:[{required: true, message: '请填写跟进内容', trigger: 'blur'},],
        isInvalid:[{required: true, message: '此项必填', trigger: 'change'},],
        developStep:[{required: true, message: '此项必填', trigger: 'change'},],
        fromBuyReason:[{required: true, message: '此项必填', trigger: 'change'},],
        cglId:[{required: true, message: '此项必填', trigger: 'change'},],
      },
      contactList:[],//联系人列表
      uploadToken:{
        token:'',
      },
      imgDomain:'',
      customerTrackingList:[],
      goodsList:[],
      popType:'',
      isBuyPermission:-1,
      payMethodList:[],
      cglCompetitorInfoList:[],
      cglCompetitorTypeList:[],
      goodsLineList:[],
      developSteps:[{name:'寻找关键人',id:10},{name:'挖掘需求',id:20},{name:'建立粘度',id:30},{name:'促成交',id:40},],
      fromBuyReasonList:[],
      querySearchList:[],


      jgList:[],
      fkList:[],
      ldList:[],
      lxrlist:[],
      lxrlistQuery:JSON.parse(JSON.stringify(defaultLxrListQuery)),
      lxrcount:0,
      lxrlistLoading:false,

      ldchcecklist:[],
      ccjlist:[],
      goodsMatchDegreeList:[],
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components : {
    addGoodsLine,addLxr
  },
  created() {

  },
  filters: {

  },
  methods:{
    //切换开发阶段
    changeDevelopStep(){
      this.lxrlist = [];
      this.trackingForm.goodsLineList = [];
      this.trackingForm.relationTypeIds = [];
      this.trackingForm.dealComparePrice = '';
      this.trackingForm.dealPayMethod = [];
      this.ldchcecklist = [];
      this.ccjlist = [];

      if(this.trackingForm.cglId.length > 0 && this.trackingForm.developStep == 10){
        this.lxrhandleSearchList(); //联系人
      }else if(this.trackingForm.cglId.length > 0 && this.trackingForm.developStep == 20){
        this.getGoodsLineInfo(); //产品线信息
      }else if(this.trackingForm.cglId.length > 0 && this.trackingForm.developStep == 30){ //粘度信息
         this.getGoodsLineLdHCcj()
      }else if(this.trackingForm.cglId.length > 0 && this.trackingForm.developStep == 40){ // 促成交
         this.getGoodsLineLdHCcj()
      }
    },

    //获取产品线促成交及粘度信息
    getGoodsLineLdHCcj(){
      goodsLineLdHCcjInfo({cglId:this.trackingForm.cglId}).then((res)=>{
         this.ccjlist = [];
         this.ldchcecklist = [];
         res.forEach((el)=>{
            this.ccjlist.push({
               cglId:el.cglId,
               goodsLineName: el.goodsLineName,
               dealPayMethod:el.dealPayMethod,
               dealComparePrice:el.dealComparePrice
            })
           this.ldchcecklist.push({
             cglId:el.cglId,
             goodsLineName: el.goodsLineName,
             chcecklist:el.chcecklist,
           })
         })
      })
    },

    //切换付款条件
    changeDealPayMethod(item,val){
      this.trackingForm.cglId.forEach((el,index)=>{
        let cunGoodsLine = this.goodsLineList.find((ee)=>{
          return ee.cglId == el
        }) // 找到当前选中产品线名称
        let cglindex = this.ccjlist.findIndex((ld)=>{
          return  ld.cglId == el
        }) //当前选中的列表是否有当前选中产品线
        if(cglindex != -1){ //有当前产品线数据
          let i = this.ccjlist[index]['dealPayMethod'].findIndex((cc)=>{
            return cc.cddId == item.cddId
          })
          let obj = JSON.parse(JSON.stringify(this.ccjlist[index]));
          if(!val){
            if(i != -1){
              obj.dealPayMethod.splice(i,1);
              this.$set(this.ccjlist,index,obj)
            }
          }else{
            if(i == -1){
              obj.dealPayMethod.push(item);
              this.$set(this.ccjlist,index,obj)
            }
          }
        }else{
          let pushObj = { cglId:el, goodsLineName: cunGoodsLine.goodsLineName,}
          pushObj.dealPayMethod = [];
          pushObj.dealComparePrice = [];
          if(val){
            pushObj.dealPayMethod.push(item)
          }
          this.ccjlist.push(pushObj)
        }
      })
    },

    //切换对比价格
    changedealComparePrice(item){
      console.log(item)
      this.trackingForm.cglId.forEach((el,index)=>{
        let cunGoodsLine = this.goodsLineList.find((ee)=>{
          return ee.cglId == el
        }) // 找到当前选中产品线名称
        let cglindex = this.ccjlist.findIndex((ld)=>{
          return  ld.cglId == el
        }) //当前选中的列表是否有当前选中产品线
        if(cglindex != -1){ //有当前产品线数据
          let obj = JSON.parse(JSON.stringify(this.ccjlist[index]));
          obj.dealComparePrice = [];
          obj.dealComparePrice.push(item);
          this.$set(this.ccjlist,index,obj)
        }else{
          let pushObj = { cglId:el, goodsLineName: cunGoodsLine.goodsLineName,}
          pushObj.dealPayMethod = [];
          pushObj.dealComparePrice = []
          pushObj.dealComparePrice.push(item)
          this.ccjlist.push(pushObj)
        }
      })
    },
    //删除对比价格
    closeSpanJg(i,ii){
      let cut = JSON.parse(JSON.stringify(this.ccjlist[i]));
      cut.dealComparePrice.splice(ii,1)
      this.$set(this.ccjlist,i,cut)
    },
    //删除付款
    closeSpanFk(i,ii){
      let cut = JSON.parse(JSON.stringify(this.ccjlist[i]));
      cut.dealPayMethod.splice(ii,1)
      this.$set(this.ccjlist,i,cut)
    },
    //删除粘度
    closeSpan(i,ii){
      let cut = JSON.parse(JSON.stringify(this.ldchcecklist[i]));
      cut.chcecklist.splice(ii,1)
      this.$set(this.ldchcecklist,i,cut)
    },

    changerelationTypeIds(item,val){
      this.trackingForm.cglId.forEach((el,index)=>{
        let cunGoodsLine = this.goodsLineList.find((ee)=>{
          return ee.cglId == el
        }) // 找到当前选中产品线名称
        let cglindex = this.ldchcecklist.findIndex((ld)=>{
          return  ld.cglId == el
        }) //当前选中的列表是否有当前选中产品线
        if(cglindex != -1){ //有当前产品线数据
            let i = this.ldchcecklist[index]['chcecklist'].findIndex((cc)=>{
              return cc.cddId == item.cddId
            })
            let obj = JSON.parse(JSON.stringify(this.ldchcecklist[index]));
            if(!val){
              if(i != -1){
                obj.chcecklist.splice(i,1);
                this.$set(this.ldchcecklist,index,obj)
              }
            }else{
              if(i == -1){
                obj.chcecklist.push(item);
                this.$set(this.ldchcecklist,index,obj)
              }
            }
        }else{
          let pushObj = { cglId:el, goodsLineName: cunGoodsLine.goodsLineName,}
          pushObj.chcecklist = [];
          if(val){
            pushObj.chcecklist.push(item)
          }
          this.ldchcecklist.push(pushObj)
        }
      })
    },


    //联系人
    lxrhandleSizeChange(val){
      this.lxrlistQuery.pageNum = 1;
      this.lxrlistQuery.pageSize = val;
      this.getlxrList();
    },
    lxrhandleCurrentChange(val){
      this.lxrlistQuery.pageNum = val;
      this.getlxrList();
    },

    lxrhandleSearchList(){
      this.lxrlistQuery.pageNum = 1;
      this.getlxrList();
    },

    //获取联系人详情列表
    getlxrList() {
      this.listLoading = true;
      this.lxrlistQuery.cglId = this.trackingForm.cglId;
      this.lxrlistQuery.customerId = this.trackingForm.customerId;
      customerNewContactList(this.lxrlistQuery).then(response => {
        this.lxrlist = response.list;
        this.lxrcount = response.count;
        this.lxrlistLoading = false;
      }).catch(()=>{
        this.lxrlistLoading = false;
      });
    },

    //客户名称输入匹配
    querySearch(queryString){
      if(queryString && queryString!= ''){
        getCustomerOption({keywords:queryString,tab:'my'}).then((res)=>{
          this.querySearchList = res;
        })
      }
    },

    //切换客户
    changeCustomer(){
      this.trackingForm.cglId = [];
      this.trackingForm.contactId = '';
      this.trackingForm.developStep = ''
      this.cut = null;
      this.goodsLineList = [];
      this.contactList = [];

      if(this.trackingForm.customerId){
        this.getList();  // 获取产品线列表
      }
      this.changeDevelopStep()
    },

    //显示增加联系人
    showAddLxr(type,item){
      let data = {}
      if(type == 'edit'){
        data = JSON.parse(JSON.stringify(item))
      }
      if(this.cut && this.cut.goodsLineId){
        data.goodsLineId = this.cut.goodsLineId
      }
      data.customerId = this.trackingForm.customerId;
      data.customerName = this.trackingForm.customerName;
      if(data.customerName == ''){
        let i = this.querySearchList.findIndex((el)=>{
          return el.customerId == data.customerId
        })
        if(i!= -1){
          data.customerName = this.querySearchList[i].customerName
        }
      }
      console.log("data",data)
      this.$refs.addLxr.showContact(type,data)
    },
    //新增产品线
    showGoodsLine(type,item){
      let data = {}
      if(type == 'edit'){
        data = JSON.parse(JSON.stringify(item))
      }
      data.customerId = this.trackingForm.customerId
      data.customerName = this.trackingForm.customerName
      this.$refs.addGoodsLine.showPop(type,data)
    },

    changecglId(){
      this.getContactListData().then(()=>{
        this.trackingForm.contactId = this.contactList[0] ? this.contactList[0].contactId:''
      });
      // this.cut = null;
      // this.cut = this.goodsLineList.find((el)=>{
      //   return el.cglId == this.trackingForm.cglId
      // });
      // this.trackingForm.developStep = this.cut.cglCurrentDevelopState
      this.trackingForm.developStep = '';
      this.trackingForm.goodsSn = '';
      // this.goodsList = [];
      // this.getGoodsList();
      this.changeDevelopStep();
    },
    getGoodsList(){
      orderGoodsList().then((res)=>{
        this.goodsList = res.list
      })
    },


    //获取产品线信息
    getGoodsLineInfo(){
      goodsLineListById({cglId:this.trackingForm.cglId}).then((res)=>{
         this.trackingForm.goodsLineList = res
      })
    },


    //切换联系人
    changeContactId(){
      let item = this.contactList.find((el)=>{
        return this.trackingForm.contactId == el.contactId
      });
      this.isBuyPermission = item.isBuyPermission
    },
    //获取七牛TOKEN
    getUploadToken(){
      getQiniuToken().then((res)=>{
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },
    //上传图片
    handleAvatarSuccess(res){
      console.log("res",res);
      this.trackingForm.trackingPics.push(this.imgDomain+res.key)
    },

    //删除图片
    delImg(index){
      this.trackingForm.trackingPics.splice(index,1)
    },
    //获取产品线列表
    getList() {
     return  developGoodsLineList({customerId:this.trackingForm.customerId,tab:'isMyCharge'}).then(response => {
        this.goodsLineList = response;
      })
    },
    //显示新增/编辑跟进
    showTracking(item,type){
      this.dialogVisible2 = true;
      this.popType = type;
      this.title2 = type == 'edit' ? '编辑跟进' : '新增跟进';
      this.trackingForm = JSON.parse(JSON.stringify(defaultTrackingForm));
      this.ldchcecklist = []
      this.ccjlist = []
      let date = new Date();
      this.getUploadToken();
      this.getCustomerSettingList();
      switch (type){
        case 'add':
          this.trackingForm.customerId = item.customerId;
          this.trackingForm.customerName = item.customerName;
          this.trackingForm.contactId = item.contactId ? item.contactId : '';
          this.trackingForm.goodsLineName = item.goodsLineName;
          this.trackingForm.cglScale = item.cglScale;
          this.trackingForm.cglOperatingRate = item.cglOperatingRate;
          this.trackingForm.cglCompetitorInfo = item.cglCompetitorInfo ? item.cglCompetitorInfo : '';
          this.trackingForm.cglCompetitorType = item.cglCompetitorType ? item.cglCompetitorType : '';
          this.trackingForm.cglMonthBuyNum = item.cglMonthBuyNum;
          this.trackingForm.cglPayMethod = item.cglPayMethod ? item.cglPayMethod : '';
          this.trackingForm.cglId = item.cglId ? [item.cglId] : [];
          this.trackingForm.developStep = item.cglCurrentDevelopStateId ? item.cglCurrentDevelopStateId : '';
          this.trackingForm.trackingTime = formatDate(date,'yyyy-MM-dd');
          this.trackingForm.trackingTypeId = this.customerTrackingList[0] ? this.customerTrackingList[0].cddId : '';
          console.log("trackingForm",this.trackingForm)
          this.getList().then(()=>{
            this.cut = null;
            this.cut = this.goodsLineList.find((el)=>{
              return el.cglId == this.trackingForm.cglId
            });
          });
          this.getContactListData().then(()=>{
            if(this.trackingForm.contactId == ''){
              this.trackingForm.contactId = this.contactList[0] ? this.contactList[0].contactId:''
            }

          })
          break;
        case 'edit':
          this.trackingForm.customerId = item.customerId;
          this.trackingForm.customerName = item.customerName;
          this.trackingForm.contactId = item.contactId ? item.contactId : '';
          this.trackingForm.goodsLineName = item.goodsLineName;
          this.trackingForm.cglScale = item.cglScale;
          this.trackingForm.cglOperatingRate = item.cglOperatingRate;
          this.trackingForm.cglCompetitorInfo = item.cglCompetitorInfo ? item.cglCompetitorInfo : '';
          this.trackingForm.cglCompetitorType = item.cglCompetitorType ? item.cglCompetitorType : '';
          this.trackingForm.cglMonthBuyNum = item.cglMonthBuyNum;
          this.trackingForm.cglPayMethod = item.cglPayMethod ? item.cglPayMethod : '';
          this.trackingForm.cglId = item.cglId;
          this.getContactListData('edit')
          this.trackingForm.trackingTime = item.trackingTime;
          this.trackingForm.trackingTypeId = item.trackingTypeId ? item.trackingTypeId : '';
          this.trackingForm.goodsSn = item.goodsSn;
          this.trackingForm.trackingId = item.trackingId ;
          this.trackingForm.trackingPics = item.trackingPics;
          this.trackingForm.trackingContent = item.trackingContent;
          this.trackingForm.nextTrackingTime = item.nextTrackingTime;
          this.trackingForm.trackingRemark = item.trackingRemark;
          this.trackingForm.isInvalid = item.isInvalid;
          this.trackingForm.developStep = item.developStepId ?  item.developStepId : '';
          this.trackingForm.fromBuyReason = item.fromBuyReason ? item.fromBuyReason : '';
          break;
        case 'addCustomer':
          this.trackingForm.customerName = item.customerName;
          this.trackingForm.customerId = item.customerId;
          this.trackingForm.trackingTime = formatDate(date,'yyyy-MM-dd');
          this.trackingForm.trackingTypeId = this.customerTrackingList[0] ? this.customerTrackingList[0].cddId : '';
          this.getList();
          break;
        case 'addMy':
          this.trackingForm.trackingTime = formatDate(date,'yyyy-MM-dd');
          this.trackingForm.trackingTypeId = this.customerTrackingList[0] ? this.customerTrackingList[0].cddId : '';
          break;
      }
      this.getGoodsList();
      this.changeDevelopStep();
    },

    //关闭跟进弹窗
    handleClose2(){
      this.$refs.trackingForm.clearValidate();
      this.dialogVisible2 = false;
      this.btnLoading2 = false;
    },

    //提交跟进
    handleConfirm2(){
      this.$refs.trackingForm.validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          let data = JSON.parse(JSON.stringify(this.trackingForm));
          data.trackingPics = data.trackingPics.join(",");
          delete data.dealComparePrice
          delete data.dealPayMethod
          data.relationTypeIds = JSON.parse(JSON.stringify(this.ldchcecklist));
          data.ccjlist = JSON.parse(JSON.stringify(this.ccjlist))
          goodsLineAddTracking(data).then((res)=>{
            this.btnLoading2 = false;
            this.handleClose2();
            this.$emit('getList');
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      })
    },

    //获取联系人列表
    getContactListData(type){
     return  getContactList({customerId:this.trackingForm.customerId,cglId:this.trackingForm.cglId}).then((res)=>{
        this.contactList = res;
        console.log("type",type)
        if(type == 'edit'){
          this.changeContactId()
        }else if(type == 'add'){
          this.lxrhandleSizeChange()
        }
      })
    },

    //获取客户配置
    getCustomerSettingList() {
      getCustomerSetting().then((res) => {
        res.forEach((el) => {
           if (el.cdtCode == 'customer_tracking') {
            this.customerTrackingList = el.data;
          }else if(el.cdtCode == 'pay_method'){
             this.payMethodList = el.data;
          }else if(el.cdtCode == 'cgl_competitor_info'){
             this.cglCompetitorInfoList = el.data;
           }else if(el.cdtCode == 'cgl_competitor_type'){
             this.cglCompetitorTypeList = el.data;
           }else if (el.cdtCode == 'from_buy_reason') {
             this.fromBuyReasonList = el.data;
           }else if(el.cdtCode == 'compare_price_type') {
            this.jgList = el.data
          }else  if(el.cdtCode == 'pay_method_type') {
            this.fkList = el.data
          }else if(el.cdtCode == 'develop_relation_type') {
            this.ldList = el.data
          }else if(el.cdtCode == 'goods_match_degree'){
             this.goodsMatchDegreeList = el.data
           }
        });
      })
    },
  },
}
</script>

<style  lang="scss">
.chceckspan{
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 20px;
  box-sizing: border-box;
  margin:5px;
  cursor: default;
  .el-tag__close{
    float: right;
    margin-top: -17px;
    margin-right: -15px;
  }
}
.chceckspan.chceckspan2 .el-tag__close{
  margin-top: 0;
}
.avatar-uploader{
  margin-bottom:10px;
  display: inline-block;
  width:80px;
  height:80px;
  border:1px solid #DCDFE6;
  text-align: center;
  line-height: 80px;
  vertical-align: middle;
}
.check-item{
  overflow: hidden;
  margin-bottom:5px;
  .el-checkbox{
    float:left;
    line-height: 20px;
  }
  .el-checkbox__label{
    display: none;
  }
  .label{
    float:left;
    width:calc(100% - 30px);
    margin-left:10px;
    line-height: 20px;
    font-size: 12px;
  }
}
</style>
